import { cancelOrderAPI, delelOrderAPI } from "@/apis/consult"
import { getMedicalOrderDetailAPI } from "@/apis/order"
import { OrderType } from "@/enums"
import type { ConsultOrderItem } from "@/types/consult"
import type { OrderDetail } from "@/types/order"
import { showFailToast, showSuccessToast } from "vant"
import { onMounted, ref } from "vue"

// 取消订单的组合式函数
export const useCancelOrder = () => {
    // 加载效果
    const onLoading = ref(false)

    const cancelConsultOrder = async (item: ConsultOrderItem) => {
        try {
            // 开启加载效果
            onLoading.value = true
            // 发请求
            await cancelOrderAPI(item.id)
            // 修改订单状态
            item.status = OrderType.ConsultCancel
            item.statusValue = '已取消'
            // 提示用户
            showSuccessToast('取消成功')
        } catch (error) {
            showFailToast('取消失败')
        } finally {
            // 关闭加载效果
            onLoading.value = false
        }
    }
    return {
        onLoading,
        cancelConsultOrder
    }
}

// 删除订单的组合式函数
export const useDeleteOrder = (consultDel: () => void) => {
    const delLoading = ref(false)

    const delelOrder = async (item: ConsultOrderItem) => {
        try {
            delLoading.value = true
            await delelOrderAPI(item.id)
            showSuccessToast('删除成功')
            // 让父组件根据id来删除订单
            // emit('on-delete', item.id)
            // emit是函数，不能在ts文件中使用
            consultDel && consultDel()
        } catch (error) {
            showFailToast('删除失败')
        } finally {
            delLoading.value = false
        }
    }
    return{
        delLoading,
        delelOrder
    }
}

// 获取订单详情的组合式函数
export const useOrderDetail = (id: string) => {
    // 保存药品订单详情
    const medOrderList = ref<OrderDetail>()

    onMounted(async () => {
        const res = await getMedicalOrderDetailAPI(id)
        // console.log(res)
        medOrderList.value = res.data
    })
    return {
        medOrderList
    }
}